import React, { Component } from 'react'

import {getDatas} from '../../../utils/tools';

import Slider from '../../../services/slider'
import CommonService from '../../../services/common'


import {SLIDER_TH} from '../../../config/table_config'
import ListTitle from '../../../components/common/ListTitle';
import TableHead from '../../../components/common/TableHead'
import TableBody from '../../../pages/sub/Slider/TableBody'

import './index.scss'

const slider = new Slider();
const commonService = new CommonService();
export default class SliderCourse extends Component {
    constructor(props){
        super(props);
        this.state={
            title:'轮播图管理',
            sliderData:[]
        }
    }
    async getSliderData(){
        const result = await slider.getSliderData(),
        errorCode = result.error_code,
        data = result.data,
        {history} = this.props;
        
        getDatas(errorCode,data,history,()=>{
          this.setState({
            sliderData:data
          })
          
        })
       
    }
    async onStatusClick(cid,index){
        const {sliderData} = this.state,
              status = sliderData[index].status;
        const cfm = window.confirm(`确定要${status? '下架':'上架'}该轮播图吗？`)   
        if(cfm){   
         switch(status){
             case 1:
                sliderData[index].status = 0;
                 break;
             case 0:
                sliderData[index].status = 1;
                 break;
             default:
                 break;        
         }    
         this.setState({
             sliderData:this.state.sliderData
         },async()=>{
             const result = await commonService.changeStatus({
                 id:cid,
                 status:this.state.sliderData[index].status,
                 field:'SLIDER'
             })
             const errorCode = result.error_code;
             if(errorCode!==0){
                 const status = this.state.sliderData[index].status;
                 alert(
                     status ? '该课程上架失败!':'该课程下架失败'
                 )
                 return
             }
         }) 
        }
    }
   componentDidMount(){
       this.getSliderData();
   }
    render() {
        const {title,sliderData} = this.state;
        return (
            <div className="list-container">
               <ListTitle title={title} onRefreshData={this.getSliderData.bind(this)} ></ListTitle>
               <table className="list-table">
               <TableHead thData={SLIDER_TH} ></TableHead>
              
               <TableBody sliderData = {sliderData} 
                
               
                onStatusClick = {this.onStatusClick.bind(this)}
               ></TableBody>
               </table>
            </div>
        )
    }
}
